﻿using MaiPlanServer.Dto;
using MaiPlanServer.IRepository;
using MaiPlanServer.IServices.IOrganizationaServices;
using MaiPlanServer.Model;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MaiPlanServer.Services.OrganizationalServices
{
    internal class DepartmentManageServices : IDepartmentManageServices
    {
        public DepartmentManageServices(IBaseRepository BaseConn)
        {
            this.BaseConn = BaseConn;
        }

        public IBaseRepository BaseConn { get; }

        public async Task<bool> AddAsync(sys_dept model)
        {
            var rusult = await BaseConn.InsertAsync(model);
            return rusult;
        }

        public async Task<bool> DelAsync(string Id)
        {
            var sql = @"with tab as (
	                select * from  sys_dept where  dept_id=@Id
	                union all 
	                select child.* from  sys_dept  child join tab parent on parent.dept_id = child.parent_id
                )
                delete sys_dept where dept_id in (select dept_id from tab)";
            var resulr = await BaseConn.DeleteAsync(sql, new { Id = Id });
            return resulr;
        }

        public async Task<IEnumerable<sys_deptDto>> GetDepartmentAsync(string DName, string State)
        {
            var sql = "select * from sys_dept where 1=1";
            if (!string.IsNullOrEmpty(DName))
            {
                sql += " and dept_name like @DName";
            }
            if (!string.IsNullOrEmpty(State))
            {
                sql += " and status =@State";
            }
            sql += " order by order_num desc";
            var list = await BaseConn.QueryAsync<sys_deptDto>(sql, new { DName = "%" + DName + "%", State = State });
            return list;
        }

        public async Task<bool> PutAsync(sys_dept moel)
        {
            var result = await BaseConn.UpdateAsync(moel, "dept_id");

            return result;
        }
    }
}
